import logging
from logging.handlers import RotatingFileHandler

from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from redis import StrictRedis
from flask_wtf.csrf import CSRFProtect
from flask_session import Session
from config import config

db = None
redis_store = None

def create_app(config_name='development'):
    setup_log(config_name)
    app = Flask(__name__)

    app.config.from_object(config[config_name])
    global db
    db = SQLAlchemy()
    db.init_app(app)
    global redis_store
    redis_store=StrictRedis(host=config[config_name].REDIS_HOST,port=config[config_name].REDIS_PORT)
    CSRFProtect(app)   # 同源策略
    Session(app)

    return app

def setup_log(config_name):


    logging.basicConfig(level=config[config_name].LOG_LEVEL)

    file_log_handler = RotatingFileHandler("logs/log", maxBytes=1024 * 1024 * 100, backupCount=10)

    formatter = logging.Formatter('%(levelname)s %(filename)s:%(lineno)d %(message)s')

    file_log_handler.setFormatter(formatter)

    logging.getLogger().addHandler(file_log_handler)